package com.epam.parser;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

public class Comparator {

	private static Logger log = Logger.getLogger(Comparator.class.getName());

	public Comparator() {
	}

	public static void getEntriesInText(Text t, String fileName) throws FileNotFoundException, IOException {
		Properties p = new Properties();
		
		for (Word w : Word.readWordsToCompare(fileName)) {
			int j = 0;
			for (TextPart e : Word.divideToWords(t)) {
				if (w.toString().equals(e.toString())) {
					j++;
				}

			}
			log.info("Number of entries for " + w.toString() + " is " + j);
			p.put(w.toString(), String.valueOf(j));
			p.store(new FileWriter("src/main/resources/entries.properties"), "");
		}

	}

	public static void sortByEntryCount(String entriesFileName, String wordsFileName)
			throws FileNotFoundException, IOException {
		Properties properties = new Properties();
		properties.load(new FileReader(entriesFileName));
		Word[] wordsArray =  Word.listToArray(((Word.readWordsToCompare(wordsFileName))));
		for (int j = 0; j < wordsArray.length; j++) {
			for (int i = 0; i < wordsArray.length; i++) {
				if ((i + 1) < wordsArray.length
						&& Integer.valueOf(properties
								.getProperty(wordsArray[i].toString())) < Integer
								.valueOf(properties
										.getProperty(wordsArray[i + 1].toString()))) {
					Word o;
					o = wordsArray[i];
					wordsArray[i] = wordsArray[i + 1];
					wordsArray[i + 1] = o;
				}
			}
		}
		log.info("Entries descending");
	}

	public static void getEntriesInSentences(Text t, String fileName) {
		int q = 1;
		for (TextPart s : Sentence.divideToSentences(t)) {
			StringTokenizer st = new StringTokenizer(s.toString(),
					" \t\n\r,.()");
			List<String> sentenceTokenized = new ArrayList<String>();
			while (st.hasMoreTokens()) {
				sentenceTokenized.add(st.nextToken());
			}
			for (Word w : Word.readWordsToCompare(fileName)) {
				int j = 0;
				for (int i = 0; i < sentenceTokenized.size(); i++) {
					if (w.toString().equals(sentenceTokenized.get(i))) {
						j++;
					}

				}
				log.info("Word " + w.toString()
						+ " appears in sentence number " + q +" " + j + " times");
			}
			q++;
		}
		
	}

}
